package com.zyf.project.capchain.controller;

import com.alibaba.fastjson.JSON;
import com.zyf.project.capchain.blockchain.service.BlockService;
import com.zyf.project.capchain.blockchain.service.PowService;
import com.zyf.project.capchain.blockchain.utils.BlockCache;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author Zhou Yifan
 */
@Slf4j
@Controller
@RequiredArgsConstructor
public class BlockController {

    private final BlockService blockService;

    private final BlockCache blockCache;

    private final PowService powService;

    /**
     * 查看当前节点区块链数据
     *
     * @return JSON数据
     */
    @GetMapping("/scan")
    @ResponseBody
    public String scanBlock() {
        return JSON.toJSONString(blockCache.getBlockChain());
    }

    /**
     * 查看当前节点区块链数据
     *
     * @return JSON数据
     */
    @GetMapping("/data")
    @ResponseBody
    public String scanData() {
        return JSON.toJSONString(blockCache.getPackedTransactions());
    }

    /**
     * 创建创世区块
     *
     * @return JSON数据
     */
    @GetMapping("/create")
    @ResponseBody
    public String createFirstBlock() {
        blockService.createGenesisBlock();
        return JSON.toJSONString(blockCache.getBlockChain());
    }

    /**
     * 工作量证明PoW，挖矿生成新的区块
     *
     * @return JSON 数据
     */
    @GetMapping("/mine")
    @ResponseBody
    public String createNewBlock() {
        powService.mine();
        return JSON.toJSONString(blockCache.getBlockChain());
    }
}
